package com.example.springapplicationdemo.handlerexceptionresolver;

import com.example.springapplicationdemo.exception.BusinessException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PageHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if(isPageRequest(handler) && isAcceptException(ex)){
            ModelAndView mv =  new ModelAndView("error");
            mv.addObject("error", ex);
            return mv;
        }
        return null;
    }


    private boolean isPageRequest(Object handler) {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            return AnnotationUtils.findAnnotation(handlerMethod.getMethod(), ResponseBody.class) == null
                    && AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), ResponseBody.class) == null;
        }
        return true;
    }

    private boolean isAcceptException(Exception ex) {
        return ex instanceof BusinessException;
    }
}
